vim9script noclear

var flag: bool
var id: number
var ratio: float = 0.3

def Preview_filter(winid: number, key: string): bool
    if key == 'q'
        popup_hide(winid)
	elseif key == "\<C-j>"
        win_execute(winid, "normal! \<c-e>")
	elseif key == "\<C-k>"
        win_execute(winid, "normal! \<c-y>")
	elseif key == "\<C-d>"
        win_execute(winid, "normal! \<c-d>")
	elseif key == "\<C-u>"
        win_execute(winid, "normal! \<c-u>")
    else
        return false
    endif

	return true
enddef

export def Show(range_args: number, line1: number, line2: number)
	var bufnr = bufnr()
	var col: number = float2nr(&columns * ratio)
    var title: string = bufnr->bufname()->fnamemodify(':~:.')
	var info = popup_getpos(id)

    id = popup_create(bufnr, {
		line: 1,
		col: &columns - col,
		minwidth: col + 2,
		maxwidth: col + 2,
		minheight: &lines,
		maxheight: &lines,
        title: title,
        close: 'none',
		tabpage: -1,
        scrollbar: 0,
        filter: Preview_filter,
        filtermode: 'n',
        mapping: false,
    })

	if range_args > 0
		win_execute(id, $"normal! {line1}G|zt")
	else
		win_execute(id, $"normal! {line('.')}G|zt")
	endif
enddef

export def Toggle()
	var info = popup_getpos(id)

	if empty(info)
		return
	endif

	if info.visible == 1
		popup_hide(id)
	else
		popup_show(id)
	endif
enddef

export def Set(fnum: float = 0.3)
	var col: number = float2nr(&columns * fnum)

	ratio = fnum
	popup_setoptions(id, {
		col: &columns - col,
		minwidth: col + 2,
		maxwidth: col + 2,
	})
enddef
